<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI助手</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }
        body {
            background: linear-gradient(135deg, #e6f7ff 0%, #f0f0ff 40%, #f9f0ff 100%);
            color: #333;
            min-height: 100vh;
            padding: 20px 20px;
        }

        .container {
            max-width: 900px; /* 从1200px缩减到900px */
            margin: 0 auto;
            background: white;
            border-radius: 24px;
            overflow: hidden;
            box-shadow: 0 12px 40px rgba(24, 144, 255, 0.15);
            position: relative;
        }

        .container::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            height: 4px;
            background: linear-gradient(90deg, #1890ff, #722ed1);
        }

        .header {
            text-align: center;
            padding: 20px 0 25px;
            border-bottom: 1px solid #f0f0f0;
        }

        .header h1 {
            font-size: 28px;
            font-weight: 600;
            color: #2c3e50;
            position: relative;
            display: inline-block;
            letter-spacing: 1.5px;
        }

        .header h1::after {
            content: '';
            position: absolute;
            bottom: -15px;
            left: 50%;
            transform: translateX(-50%);
            width: 60px;
            height: 3px;
            background: linear-gradient(90deg, #1890ff, #722ed1);
            border-radius: 3px;
        }

        .chat-container {
            flex: 1;
            overflow-y: auto;
            padding: 35px 40px; /* 减少左右内边距 */
            display: flex;
            flex-direction: column;
            gap: 30px;
            scroll-behavior: smooth;
            min-height: 60vh;
            max-height: 70vh;
        }

        .chat-message {
            display: flex;
            gap: 24px;
            max-width: 75%; /* 从80%缩减到75%，使消息气泡更紧凑 */
            animation: fadeIn 0.3s ease;
        }

        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }

        .chat-message.user {
            align-self: flex-end;
            flex-direction: row-reverse;
        }

        .avatar {
            width: 50px;
            height: 50px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            flex-shrink: 0;
            box-shadow: 0 4px 12px rgba(24, 144, 255, 0.15);
            font-weight: 500;
            font-size: 18px;
        }

        .avatar.ai {
            background: linear-gradient(135deg, #f0f9ff, #e6f7ff);
            color: #1890ff;
            border: 1px solid #e6f7ff;
        }

        .avatar.user {
            background: linear-gradient(135deg, #f9f0ff, #f5e6ff);
            color: #722ed1;
            border: 1px solid #f5e6ff;
        }

        .message-bubble {
            padding: 20px 26px; /* 微调气泡内边距 */
            border-radius: 20px;
            line-height: 1.6;
            word-break: break-word;
            font-size: 16px;
            box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
        }

        .message-bubble.ai {
            background-color: #fafafa;
            color: #333;
            border-top-left-radius: 8px;
        }

        .message-bubble.user {
            background: linear-gradient(135deg, #1890ff, #096dd9);
            color: white;
            border-top-right-radius: 8px;
        }

        .typing-indicator {
            display: flex;
            gap: 6px;
            padding: 12px;
            align-items: center;
        }

        .typing-indicator span {
            width: 12px;
            height: 12px;
            background-color: #91d5ff;
            border-radius: 50%;
            animation: typing 1.4s infinite ease-in-out both;
        }

        .typing-indicator span:nth-child(1) { animation-delay: -0.32s; }
        .typing-indicator span:nth-child(2) { animation-delay: -0.16s; }

        @keyframes typing {
            0%, 80%, 100% { transform: scale(0); }
            40% { transform: scale(1); }
        }

        .input-container {
            padding: 25px 40px 30px; /* 减少左右内边距 */
            background: white;
            border-top: 1px solid #f5f5f5;
        }

        .input-wrapper {
            position: relative;
            border-radius: 28px;
            overflow: hidden;
        }

        #userInput {
            width: 100%;
            padding: 18px 120px 18px 28px;
            border: 1px solid #e8e8e8;
            border-radius: 28px;
            font-size: 16px;
            resize: none;
            height: 58px;
            line-height: 24px;
            background: #fafafa;
            color: #333;
            transition: all 0.3s ease;
        }

        #userInput:focus {
            outline: none;
            border-color: #91d5ff;
            box-shadow: 0 0 0 4px rgba(24, 144, 255, 0.12);
            background: white;
        }

        #sendBtn {
            position: absolute;
            right: 14px;
            bottom: 14px;
            width: 52px;
            height: 52px;
            border-radius: 50%;
            background: linear-gradient(135deg, #1890ff, #722ed1);
            color: white;
            border: none;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: all 0.2s;
            font-size: 20px;
            box-shadow: 0 4px 16px rgba(24, 144, 255, 0.2);
        }

        #sendBtn:hover {
            transform: scale(1.06);
            box-shadow: 0 5px 20px rgba(24, 144, 255, 0.3);
            background: linear-gradient(135deg, #2b9eff, #8540e0);
        }

        #sendBtn:disabled {
            background: linear-gradient(135deg, #a0cfff, #c2a0e9);
            cursor: not-allowed;
            transform: scale(1);
            box-shadow: none;
        }

        .system-prompt {
            background: linear-gradient(135deg, #f0f9ff, #f8f4ff);
            padding: 16px 20px;
            border-radius: 14px;
            font-size: 15px;
            color: #596a80;
            border-left: 3px solid #91d5ff;
            margin-bottom: 10px;
        }
    </style>
</head>
<body>
<div class="container">
    <div class="header">
        <h1>AI助手</h1>
    </div>
    <div class="chat-container" id="chatContainer">
        <div class="system-prompt">
            我是AI助手，可以回答您的问题。请输入您想了解的内容...
        </div>
    </div>
    <div class="input-container">
        <div class="input-wrapper">
            <textarea id="userInput" placeholder="输入您的问题..."></textarea>
            <button id="sendBtn">➤</button>
        </div>
    </div>
</div>

<script>
    document.addEventListener('DOMContentLoaded', function() {
        const userInput = document.getElementById('userInput');
        const sendBtn = document.getElementById('sendBtn');
        const chatContainer = document.getElementById('chatContainer');
        let eventSource = null;

        // 初始化SSE连接
        function initSseConnection() {
            const baseUrl = window.location.origin;
            const sseUrl = `http://localhost:8081/sse/subscribe`;
            console.log("尝试连接SSE:", sseUrl);

            if (eventSource) {
                eventSource.close();
                console.log("已关闭之前的SSE连接");
            }

            eventSource = new EventSource(sseUrl);
            eventSource.onopen = function() {
                console.log("SSE连接已建立，等待工具调用通知...");
            };

            eventSource.addEventListener("toolInvoke", function(event) {
                console.log("收到工具调用通知:", event.data);
                showToolNotify(event.data);
            });

            eventSource.onerror = function(error) {
                console.error("SSE连接错误:", error);
                if (eventSource.readyState === EventSource.CONNECTING) {
                    console.log("SSE连接断开，将在3秒后尝试重连...");
                    setTimeout(initSseConnection, 3000);
                }
            };
        }

        function showToolNotify(message) {
            if (!toolNotifyPopup) return;

            let toolName = "未知工具";
            if (message.includes("工具【")) {
                const match = message.match(/工具【(.*?)】/);
                if (match && match[1]) toolName = match[1];
            } else if (message.includes("调用了")) {
                const match = message.match(/调用了(.*?)，/);
                if (match && match[1]) toolName = match[1];
            }

            toolNotifyPopup.textContent = `正在调用${toolName}工具`;
            toolNotifyPopup.classList.add('show');
            void toolNotifyPopup.offsetWidth;

            setTimeout(() => {
                toolNotifyPopup.classList.remove('show');
            }, 3000);
        }

        userInput.addEventListener('input', () => {
            userInput.style.height = 'auto';
            const newHeight = Math.min(userInput.scrollHeight, 120);
            userInput.style.height = `${newHeight}px`;
        });

        sendBtn.addEventListener('click', sendMessage);
        userInput.addEventListener('keydown', (e) => {
            if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                sendMessage();
            }
        });

        async function sendMessage() {
            const message = userInput.value.trim();
            if (!message) return;

            addMessageToChat(message, 'user');
            userInput.value = '';
            userInput.style.height = '58px';
            sendBtn.disabled = true;

            const typingIndicator = addTypingIndicator();

            try {
                const response = await fetch(`http://localhost:8081/ai?userInput=${encodeURIComponent(message)}`);
                if (!response.ok) {
                    throw new Error(`请求失败: ${response.status}`);
                }

                if (typingIndicator.parentNode === chatContainer) {
                    chatContainer.removeChild(typingIndicator);
                }

                const aiMessageElement = addMessageToChat('', 'ai', true);
                const messageBubble = aiMessageElement.querySelector('.message-bubble');

                const reader = response.body.getReader();
                const decoder = new TextDecoder('utf-8');

                try {
                    while (true) {
                        const { done, value } = await reader.read();
                        if (done) break;
                        const text = decoder.decode(value, { stream: true });
                        messageBubble.textContent += text;
                        chatContainer.scrollTop = chatContainer.scrollHeight;
                    }
                } finally {
                    reader.releaseLock();
                }
            } catch (error) {
                if (typingIndicator.parentNode === chatContainer) {
                    chatContainer.removeChild(typingIndicator);
                }

                if (error.name === 'TypeError') {
                    addMessageToChat(`网络错误: 无法连接到服务器，请检查后端是否已启动`, 'ai');
                } else {
                    addMessageToChat(`发生错误: ${error.message}`, 'ai');
                }
                console.error('详细错误信息:', error);
            } finally {
                sendBtn.disabled = false;
            }
        }

        function addMessageToChat(text, sender, isStreaming = false) {
            const messageDiv = document.createElement('div');
            messageDiv.className = `chat-message ${sender}`;

            const avatarDiv = document.createElement('div');
            avatarDiv.className = `avatar ${sender}`;
            avatarDiv.textContent = sender === 'user' ? '你' : 'AI';

            const bubbleDiv = document.createElement('div');
            bubbleDiv.className = `message-bubble ${sender}`;
            bubbleDiv.textContent = text;

            messageDiv.appendChild(avatarDiv);
            messageDiv.appendChild(bubbleDiv);
            chatContainer.appendChild(messageDiv);
            chatContainer.scrollTop = chatContainer.scrollHeight;

            return isStreaming ? messageDiv : null;
        }

        function addTypingIndicator() {
            const typingDiv = document.createElement('div');
            typingDiv.className = 'chat-message ai';

            const avatarDiv = document.createElement('div');
            avatarDiv.className = 'avatar ai';
            avatarDiv.textContent = 'AI';

            const indicatorDiv = document.createElement('div');
            indicatorDiv.className = 'typing-indicator message-bubble ai';
            indicatorDiv.innerHTML = '<span></span><span></span><span></span>';

            typingDiv.appendChild(avatarDiv);
            typingDiv.appendChild(indicatorDiv);
            chatContainer.appendChild(typingDiv);
            chatContainer.scrollTop = chatContainer.scrollHeight;

            return typingDiv;
        }

        window.addEventListener('beforeunload', function() {
            console.log("页面即将卸载，正在清理资源...");
            if (eventSource) {
                eventSource.close();
                console.log("SSE连接已关闭。");
            }
        });

        initSseConnection();
    });
</script>
</body>
</html>